package cn.flying.cloud.base.common.validate;


import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.Validator;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.hibernate.validator.HibernateValidator;
import org.springframework.util.StringUtils;

/**
 * 参数验证工具类
 *
 * @author: admin
 * @date: 2023年02月15日 13:44
 * @version: 1.0
 */
public class ValidationUtil {

    private static Validator validatorAll = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();
    private static Validator validatorFastFail = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 校验所有参数
     *
     * @param o
     * @param groups
     */
    public static void validate(Object o, Class<?>... groups) {
        Set<ConstraintViolation<Object>> violationSet = validatorAll.validate(o, groups);
        if (!StringUtils.isEmpty(violationSet)) {
            throw new ConstraintViolationException(violationSet);
        }
    }

    /**
     * 校验参数，发现一个即返回
     *
     * @param o
     * @param groups
     */
    public static void validateFastFail(Object o, Class<?>... groups) {
        Set<ConstraintViolation<Object>> violationSet = validatorFastFail.validate(o, groups);
        if (!StringUtils.isEmpty(violationSet)) {
            throw new ConstraintViolationException(violationSet);
        }
    }

    /**
     * 校验所有参数
     *
     * @param o
     * @param groups
     */
    public static Map<String, String> valid(Object o, Class<?>... groups) {
        Map<String, String> map = new HashMap<>();
        Set<ConstraintViolation<Object>> violationSet = validatorAll.validate(o, groups);
        if (!StringUtils.isEmpty(violationSet)) {
            for (ConstraintViolation<Object> violation : violationSet) {
                map.put(violation.getPropertyPath().toString(), violation.getMessage());
            }
        }
        return map;
    }
}
